/**
 * Created by Dima on 15.01.2015.
 */
var manager = {
    ajaxJsonCall: function(url, data, requestType, onSuccess){
        console.log(url +" "+data+" "+requestType);
        $.ajax({
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(data),
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            type: requestType,
            success: function(data) {
                if(data.errorMessage)
                {
                    showError(data.errorMessage);
                }
                else
                {
                    onSuccess(data);
                    console.log(url + " OK");
                }

            },
            error: function(){
                console.log(url + " ERROR");
            }
        });
    },

    ajaxPostJsonCall: function(url, data, onSuccess){
        this.ajaxJsonCall(url, data, "POST", onSuccess);
    },

    ajaxGetJsonCall: function(url, data, onSuccess){
        this.ajaxJsonCall(url, data, "GET", onSuccess);
    },

    fetchPosts:function(){
        this.ajaxPostJsonCall(
            "/messages/fetch",
            {"offset": 0, "count": 500},
            function(data){
                $("#posts_container").html("");
                $("#postsTmpl")
                    .tmpl([{"data":data}])
                    .appendTo($("#posts_container"));
            });
    },

    deletePost: function(postId){
        var that = this;
        this.ajaxPostJsonCall(
            "/messages/delete",
            {"messageId": postId},
            function(data){
                that.fetchPosts();
            });
    },

    showComments: function(postId){
        this.ajaxGetJsonCall(
            "/comments/fetch/" + postId, {},
            function(data){
                var comments = $("#comments_to_post_" + postId);
                comments.addClass("opened");
                comments.html("");
                $('#commentsTmpl')
                    .tmpl([{"data":data, "postId":postId}])
                    .appendTo("#comments_to_post_" + postId);
            });
    },

    editPost: function (postId) {
        var that = this;
        var inputName = "edit_" + postId;
        this.ajaxPostJsonCall(
            "/messages/edit",
            {"postText": $("textarea[name="+inputName+"]").val(),
             "id":postId},
            function (data) {
                that.fetchPosts();
            });
    },

    sendPost: function() {

        var formData = new FormData();
        formData.append('messageText', $('.send_message > textarea[name="messageText"]').value);
        formData.append('imageInput', $('.send_message > input[name="imageInput"]')[0].files[0]);

        $.ajax({
            url: "/messages/create",
            type: "POST",
            data: formData,
            async: false,
            contentType: false,
            //contentType: "multipart/form-data",
            processData: false,
            cache: false,
            success: function(data) {
                if (!data.errorMessage) {
                    manager.fetchPosts();

                } else {
                    showError(data.errorMessage);
                }

                },
            error: function(){
                console.log(" ERROR");
            }
        });
    },

    sendComment:function(postId){
        var that = this;
        var elementName = 'comment_'+postId;
        var post = $("textarea[name="+elementName+"]").val();
        this.ajaxPostJsonCall(
            "/comments/post",
            {"message": post, "postId": postId},
            function(data){
                that.showComments(postId);
            });

    },
    showEditForm: function (postId) {
        this.ajaxGetJsonCall(
            "/messages/fetch/" + postId,{},
            function (data) {
                var editForm = $("#edit_form_" + postId);
                editForm.addClass("opened");
                $('#editFormTmpl')
                    .tmpl([{"postText": data["postText"], "postId": postId}])
                    .appendTo("#edit_form_" + postId);

            });
    }
};

function getMessageText() {
    return $("textarea[name='message']").val();
}